package com.abacus.salary.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class SessionProvider {
	private static final SessionFactory sessionFactory;
	private static final String cfgPath = "/config/hibernate/hibernate.cfg.xml";
	static {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			sessionFactory = new Configuration().configure(cfgPath).buildSessionFactory();
		} catch (Throwable e) {
			// Make sure you log the exception, as it might be swallowed
			throw new ExceptionInInitializerError(e);
		}
	}
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

	public static synchronized final Session getCurrentSession() {
		Session session = threadLocal.get();
		if (null == session || !session.isOpen()) {
			session = sessionFactory.getCurrentSession();
			if (null == session) {
				session = sessionFactory.openSession();
				threadLocal.set(session);
			}
		}
		return session;
	}
}
